﻿/*
 * 作者: 谢中涞,博客园:http://www.cnblogs.com/xie-zhonglai
 * 欢迎转载,但请保留出处
 * */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Xiezl.Common.LinqEx;

namespace Xiezl.Common.EFExpressions
{
    /// <summary>
    /// 构建类似于查询条件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    internal class LikeEFExpression<T> : EFExpression<T> where T : class
    {
        /// <summary>
        /// 定义条件的实体属性
        /// </summary>
        private Expression<Func<T, string>> property;

        /// <summary>
        /// 比较的值
        /// </summary>
        private string val;

        /// <summary>
        /// 构建新的类似于查询条件
        /// </summary>
        /// <param name="property"></param>
        /// <param name="val"></param>
        public LikeEFExpression(Expression<Func<T, string>> property, string val)
        {
            if (property == null)
                throw new ArgumentNullException("property");

            this.property = property;
            this.val = val;
        }

        internal override Expression Expression
        {
            get
            {
                if (_Expression == null)
                {
                    if (!string.IsNullOrEmpty(val))
                    {
                        var propertyBody = GetMemberExpression(this, property);
                        var tempExp = Expression.Call(propertyBody,
                                        typeof(string).GetMethod("Contains", new Type[] { typeof(string) }),
                                        Expression.Constant(val)
                                    );
                        _Expression = tempExp;

                    }
                } return _Expression;
            }
        }
    }
}
